package sy.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import sy.dao.GglDaoI;
import sy.model.Tggl;
import sy.pageModel.DataGrid;
import sy.pageModel.PageHelper;
import sy.service.GglServiceI;
@Service
public class GglServiceImpl implements GglServiceI {
	@Autowired
	private GglDaoI gglDao;
	
	@Override
	public void delete(String id) {
		gglDao.delete(gglDao.get(Tggl.class, id));
	}

	@Override
	public void add(Tggl ad) throws Exception {
		Tggl u = new Tggl();
		
		u.setId(UUID.randomUUID().toString());
		u.setCreatetime(new Date().getTime()+"");
		u.setNumber(ad.getNumber());
		u.setStatus(ad.getStatus());
		gglDao.save(u);
	}
	
	@Override
	public Tggl getLastGgl(){
		String hql="from Tggl where 1=1";
		List<Tggl> tggls=gglDao.find(hql);
		
		if(tggls.size()>0){
			return tggls.get(tggls.size()-1);
		}
		return null;
	}
	@Override
	public void updateGgl(Tggl tggl){
		
		gglDao.update(tggl);
		
	}
	private String orderHql(PageHelper ph) {
		String orderString = "";
		if (ph.getSort() != null && ph.getOrder() != null) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}
	@Override
	public DataGrid dataGrid(Tggl user, PageHelper ph) {
		DataGrid dg = new DataGrid();
		List<Tggl> ul = new ArrayList<Tggl>();
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from Tggl t ";
		List<Tggl> l = gglDao.find(hql + whereHql(user, params) + orderHql(ph), params, ph.getPage(), ph.getRows());
		if (l != null && l.size() > 0) {
			for (Tggl t : l) {
				Tggl u = new Tggl();
				BeanUtils.copyProperties(t, u);
				ul.add(u);
			}
		}
		dg.setRows(ul);
		dg.setTotal(gglDao.count("select count(*) " + hql + whereHql(user, params), params));
		return dg;
	}
	private String whereHql(Tggl tad, Map<String, Object> params) {
		String hql = "";
		if (tad != null) {
			hql += " where 1=1 ";
			if (tad.getNumber() != null) {
				hql += " and t.number = :number";
				params.put("number", tad.getNumber());
			}
			
			hql += " and t.status = :status";
			params.put("status",tad.getStatus() );
		
		}
		return hql;
	}

	@Override
	public List<Tggl> getTggl() {
		
		String hql = " from Tggl t ";
		List<Tggl> l = gglDao.find(hql);
		
		return l;
	}
}
